<?php
/**
 * Talents come from diligence, and knowledge is gained by accumulation.
 *
 * @author: 晋<657306123@qq.com>
 */

namespace Xin\Filesystem;

use League\Flysystem\Adapter\CanOverwriteFiles;
use League\Flysystem\Filesystem as BaseFilesystem;
use League\Flysystem\Util;

class Filesystem extends BaseFilesystem implements FilesystemInterface{

	/**
	 * @var AdapterInterface
	 */
	protected $adapter;

	/**
	 * Filesystem constructor.
	 *
	 * @param \Xin\Filesystem\AdapterInterface $adapter
	 * @param mixed                            $config
	 */
	public function __construct(AdapterInterface $adapter, $config = null){
		parent::__construct($adapter, $config);

		$this->config->set('disable_asserts', true);
	}

	/**
	 * @return \Xin\Filesystem\AdapterInterface
	 */
	public function getAdapter(){
		return $this->adapter;
	}

	/**
	 * @inheritdoc
	 */
	public function put($path, $contents, array $config = []){
		$path = Util::normalizePath($path);
		$config = $this->prepareConfig($config);

		if(!$this->getAdapter() instanceof CanOverwriteFiles){
			return (bool)$this->getAdapter()->update($path, $contents, $config);
		}

		return (bool)$this->getAdapter()->write($path, $contents, $config);
	}

	/**
	 * @inheritdoc
	 */
	public function putStream($path, $resource, array $config = []){
		if(!is_resource($resource)){
			throw new \InvalidArgumentException(__METHOD__.' expects argument #2 to be a valid resource.');
		}

		$path = Util::normalizePath($path);
		$config = $this->prepareConfig($config);
		Util::rewindStream($resource);

		if(!$this->getAdapter() instanceof CanOverwriteFiles){
			return (bool)$this->getAdapter()->updateStream($path, $resource, $config);
		}

		return (bool)$this->getAdapter()->writeStream($path, $resource, $config);
	}

	/**
	 * @inheritdoc
	 */
	public function listContents($directory = '', $recursive = false){
		$directory = Util::normalizePath($directory);
		return $this->getAdapter()->listContents($directory, $recursive);
	}

	/**
	 * @inheritDoc
	 */
	public function getUploadToken($key = null, $expires = 3600, $policy = null, $strictPolicy = true){
		return $this->getAdapter()->getUploadToken($key, $expires, $policy, $strictPolicy);
	}

	/**
	 * @inheritDoc
	 */
	public function getPrivateFileUrl($baseUrl, $expires = 3600){
		return $this->getAdapter()->getPrivateFileUrl($baseUrl, $expires);
	}

	/**
	 * @inheritDoc
	 */
	public function getLastError(){
		return $this->getAdapter()->getLastError();
	}
}
